<?php
/**
 * 法院控制器
 */

declare (strict_types = 1);

namespace app\controller\lawcase;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class Court extends BaseController
{
    /**
     * 查看法院列表
     */
    public function list()
    {
        $param = Request::param();
        $page = isset($param['page']) ? (int)$param['page'] : 1;
        $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
        
        // 构建查询条件
        $where = [];
        $where[] = ['delete_time', '=', 0];
        
        // 关键词搜索
        if (!empty($param['keywords'])) {
            $where[] = ['name|address', 'like', '%' . trim($param['keywords']) . '%'];
        }
        
        // 按状态筛选
        if (isset($param['status']) && $param['status'] !== '') {
            $where[] = ['status', '=', $param['status']];
        }
        
        try {
            // 查询法院列表
            $list = Db::name('court')
                ->where($where)
                ->page($page, $limit)
                ->order('id', 'asc')
                ->select()
                ->each(function($item) {
                    // 格式化时间
                    $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                    $item['update_time'] = date('Y-m-d H:i', $item['update_time']);
                    
                    // 获取省市区中文名称
                    $item['province_name'] = $this->getRegionName($item['provinceid']);
                    $item['city_name'] = $this->getRegionName($item['cityid']);
                    $item['district_name'] = $this->getRegionName($item['distid']);
                    
                    // 拼接完整地址
                    $item['full_address'] = $item['province_name'] . $item['city_name'] . $item['district_name'] . $item['address'];
                    
                    return $item;
                });
            
            // 查询总数
            $count = Db::name('court')
                ->where($where)
                ->count();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 查看单个法院信息
     */
    public function view()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            // 查询法院详情
            $court = Db::name('court')
                ->where('id', $param['id'])
                ->find();
            
            if (!$court) {
                return json(['code' => 404, 'msg' => '法院信息不存在']);
            }
            
            // 格式化时间
            $court['create_time'] = date('Y-m-d H:i', $court['create_time']);
            $court['update_time'] = date('Y-m-d H:i', $court['update_time']);
            
            // 获取省市区中文名称
            $court['province_name'] = $this->getRegionName($court['provinceid']);
            $court['city_name'] = $this->getRegionName($court['cityid']);
            $court['district_name'] = $this->getRegionName($court['distid']);
            
            // 拼接完整地址
            $court['full_address'] = $court['province_name'] . $court['city_name'] . $court['district_name'] . $court['address'];
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $court
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取启用的法院列表（用于下拉选择）
     */
    public function set()
    {
        try {
            $list = Db::name('court')
                ->where('status', 1)
                ->where('delete_time', 0)
                ->order('id', 'asc')
                ->select()
                ->each(function($item) {
                    // 获取省市区中文名称
                    $item['province_name'] = $this->getRegionName($item['provinceid']);
                    $item['city_name'] = $this->getRegionName($item['cityid']);
                    $item['district_name'] = $this->getRegionName($item['distid']);
                    
                    // 拼接完整地址
                    $item['full_address'] = $item['province_name'] . $item['city_name'] . $item['district_name'] . $item['address'];
                    
                    return $item;
                });
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取地区名称
     */
    private function getRegionName($regionId)
    {
        if (empty($regionId)) {
            return '';
        }
        
        try {
            $region = Db::name('region')
                ->where('id', $regionId)
                ->find();
            
            return $region ? $region['name'] : '';
        } catch (\Exception $e) {
            return '';
        }
    }
    
    /**
     * 新增法院
     */
    public function add()
    {
        $param = Request::param();
        \think\facade\Log::info('新增法院参数: ' . json_encode($param));
        
        // 数据验证
        if (empty($param['court_name'])) {
            return $this->error('法院名称不能为空');
        }
        
        // 检查地区字段
        if (empty($param['province']) || empty($param['city']) || empty($param['district'])) {
            return $this->error('请选择完整的地区信息');
        }
        
        $data = [
            'name' => $param['court_name'],
            'level' => $param['level'] ?? 4, // 默认基层法院
            'provinceid' => $param['province'] ?? 0,
            'cityid' => $param['city'] ?? 0,
            'distid' => $param['district'] ?? 0,
            'address' => $param['address'] ?? '',
            'status' => $param['status'] ?? 1,
            'create_time' => time(),
            'update_time' => time()
        ];
        
        try {
            \think\facade\Log::info('插入法院数据: ' . json_encode($data));
            $courtId = Db::name('court')->insertGetId($data);
            \think\facade\Log::info('法院添加成功，ID: ' . $courtId);
            
            return $this->success(['id' => $courtId], '添加成功');
        } catch (\Exception $e) {
            \think\facade\Log::error('添加法院失败: ' . $e->getMessage());
            return $this->error('添加失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 编辑法院
     */
    public function edit()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['id'])) {
            return $this->error('参数错误');
        }
        
        if (empty($param['court_name'])) {
            return $this->error('法院名称不能为空');
        }
        
        $data = [
            'id' => $param['id'],
            'name' => $param['court_name'],
            'level' => $param['level'] ?? 1,
            'provinceid' => $param['province'] ?? 0,
            'cityid' => $param['city'] ?? 0,
            'distid' => $param['district'] ?? 0,
            'address' => $param['address'] ?? '',
            'status' => $param['status'] ?? 1,
            'update_time' => time()
        ];
        
        try {
            Db::name('court')->update($data);
            
            return $this->success('编辑成功');
        } catch (\Exception $e) {
            return $this->error('编辑失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 删除法院（软删除）
     */
    public function del()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return $this->error('参数错误');
        }
        
        try {
            // 检查是否有相关案件
            $caseCount = Db::name('lawcase')
                ->where('court_id', $param['id'])
                ->where('delete_time', 0)
                ->count();
            
            if ($caseCount > 0) {
                return $this->error('该法院下有关联案件，不能删除');
            }
            
            Db::name('court')
                ->where('id', $param['id'])
                ->update([
                    'delete_time' => time(),
                    'update_time' => time()
                ]);
            
            return $this->success('删除成功');
        } catch (\Exception $e) {
            return $this->error('删除失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 查看法院电话列表
     */
    public function phone_list()
    {
        $param = Request::param();
        
        if (empty($param['court_id'])) {
            return $this->error('参数错误');
        }
        
        try {
            $list = Db::name('court_phone')
                ->where('court_id', $param['court_id'])
                ->where('delete_time', 0)
                ->select()
                ->each(function($item) {
                    // 格式化时间
                    $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                    $item['update_time'] = date('Y-m-d H:i', $item['update_time']);
                    return $item;
                });
            
            return $this->success($list, 'success');
        } catch (\Exception $e) {
            return $this->error('获取失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 添加法院电话
     */
    public function phone_add()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['court_id'])) {
            return $this->error('法院ID不能为空');
        }
        
        if (empty($param['phone'])) {
            return $this->error('电话号码不能为空');
        }
        
        $data = [
            'court_id' => $param['court_id'],
            'phone' => $param['phone'],
            'type' => $param['type'] ?? 1, // 1:办公电话 2:传真
            'remark' => $param['remark'] ?? '',
            'create_time' => time(),
            'update_time' => time()
        ];
        
        try {
            $phoneId = Db::name('court_phone')->insertGetId($data);
            
            return $this->success(['id' => $phoneId], '添加成功');
        } catch (\Exception $e) {
            return $this->error('添加失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 编辑法院电话
     */
    public function phone_edit()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['id'])) {
            return $this->error('参数错误');
        }
        
        if (empty($param['phone'])) {
            return $this->error('电话号码不能为空');
        }
        
        $data = [
            'id' => $param['id'],
            'phone' => $param['phone'],
            'type' => $param['type'] ?? 1,
            'remark' => $param['remark'] ?? '',
            'update_time' => time()
        ];
        
        try {
            Db::name('court_phone')->update($data);
            
            return $this->success('编辑成功');
        } catch (\Exception $e) {
            return $this->error('编辑失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 删除法院电话（软删除）
     */
    public function phone_del()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return $this->error('参数错误');
        }
        
        try {
            Db::name('court_phone')
                ->where('id', $param['id'])
                ->update([
                    'delete_time' => time(),
                    'update_time' => time()
                ]);
            
            return $this->success('删除成功');
        } catch (\Exception $e) {
            return $this->error('删除失败: ' . $e->getMessage());
        }
    }
}